<template>
  <div class="energy_consume">
    <div class="top_query">
      <div class="tabs">
        <px-radio-group v-model="queryTypeParams.energyType" class="tabSwitch" @change="handleChangeTypeFn">
          <px-radio-button :label="1">电</px-radio-button>
          <px-radio-button :label="2">自来水</px-radio-button>
          <px-radio-button :label="16">天然气</px-radio-button>
          <px-radio-button :label="3">蒸汽</px-radio-button>
          <px-radio-button :label="7">热水</px-radio-button>
          <px-radio-button :label="9">CDA</px-radio-button>
          <px-radio-button :label="10">N₂</px-radio-button>
          <px-radio-button :label="11">H₂</px-radio-button>
          <px-radio-button :label="12">O₂</px-radio-button>
          <px-radio-button :label="13">Ar</px-radio-button>
          <px-radio-button :label="14">He</px-radio-button>
          <px-radio-button :label="15">CO₂</px-radio-button>
          <!-- <px-radio-button :label="4">柴油</px-radio-button> -->
        </px-radio-group>
      </div>
      <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
        <px-form-item label="时间范围" style="width: 430px">
          <px-date-picker
            v-model="dateRangeItem"
            :clearable="false"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </px-form-item>
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form>
    </div>
    <div v-if="queryTypeParams.energyType === 1" class="top-wrap">
      <px-radio-group v-model="radioVal" @change="handleRadioChange">
        <px-radio-button :label="17">MV10</px-radio-button>
        <px-radio-button :label="18">MV20</px-radio-button>
        <px-radio-button :label="19">MV30</px-radio-button>
        <px-radio-button :label="20">MV40</px-radio-button>
      </px-radio-group>
    </div>
    <div class="btn-con">
      <div class="btn-bord">
        <div class="rightBox">
          <px-button v-if="showCon" v-has="'ALL_ENERGY_PREDICT_BEAR_DOWNLOAD'" @click="handleDown">
            导出<px-icon class="px-icon--right">
              <Download />
            </px-icon>
          </px-button>
        </div>
        <bearBordchart
          v-if="showCon"
          :key="midKey"
          title="负荷趋势"
          :unit="getUnit"
          :dataList="loadOviewData"
          :width="642"
          :height="505"
          :options="yearOptions"
          :timeFrame="dateRangeItem"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_PREDICT_BEAR"
});
import { ref, reactive, toRefs, getCurrentInstance, onMounted, computed } from "vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import bearBordchart from "../components/bearBordchart.vue";
import { getBearPredictData } from "@/api/energy/predictApi";
// import EnergyConsumeRank from "@/views/common/energy/components/EnergyConsumeRank.vue";
import { Download } from "@px-ui/icons-vue";

const { proxy }: any = getCurrentInstance();

const state = reactive({
  radioVal: 17
});

const { radioVal } = toRefs(state);

const showCon = ref(false);

const midKey = ref(Date.now());

const dateRangeItem = ref([]);

const yearOptions = ref<UtilsEChartsOption>({});

const getUnit = computed(() => {
  switch (queryTypeParams.value.energyType) {
    case 1:
      return "kva"; // 电
    case 2:
      return "m³/d"; // 水
    case 3:
      return "t/d"; // 蒸汽
    case 7:
      return "t/d"; // 热水
    case 4:
      return "t"; // 柴油
    case 5:
      return "Nm³"; // 大宗气
    case 6:
      return "Nm³"; // 大宗气
    case 9:
      return "Nm³/d"; // cda
    case 10:
      return "Nm³/d"; // N2
    case 11:
      return "Nm³/d"; // h2
    case 12:
      return "Nm³/d"; // o2
    case 13:
      return "Nm³/d"; // Ar
    case 14:
      return "Nm³/d"; // He
    case 15:
      return "Nm³/d"; // co2
    case 16:
      return "Nm³/d"; // 天然气

    default:
      return "kva";
  }
});

// 年度总览
const loadOviewData = ref(null);
// 月度明细
const monthlyDetails = ref(null);
type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const transformNumber = val => {
  const arr = val.split(",");
  if (arr.length) {
    return arr.join("");
  }
  return val;
};

// 获取纵轴最大值和最少值
let getMinYMaxY = (data: object) => {
  data.kwhCoordinate = data.kwhCoordinate.map(item => transformNumber(item));
  data.kwhPredictCoordinate = data.kwhPredictCoordinate.map(item => transformNumber(item));
  let maxCoorY = data.kwhCoordinate.reduce((pre, cur) => {
    if (Number(cur) > 0) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minCoorY = data.kwhCoordinate.reduce((pre, cur) => {
    if (Number(cur) > 0) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number([pre]);
    }
  }, maxCoorY);
  let maxPredictY = data.kwhPredictCoordinate.reduce((pre, cur) => {
    if (Number(cur) > 0) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minPredictY = data.kwhPredictCoordinate.reduce((pre, cur) => {
    if (Number(cur) > 0) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, maxPredictY);
  let maxY = maxCoorY > maxPredictY ? maxCoorY : maxPredictY;
  let minY;
  if (minCoorY > 0) {
    if (minPredictY > 0) {
      minY = minCoorY < minPredictY ? minCoorY : minPredictY;
    } else {
      minY = minCoorY;
    }
  } else {
    minY = minPredictY;
  }
  maxY = (maxY * 1.2).toFixed(2);
  minY = (minY * 0.8).toFixed(2);
  let maxrcY = data.radioCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) > Number([pre]) ? Number(cur) : Number(pre);
    } else {
      return Number(pre);
    }
  }, 0);
  let minrcY = data.radioCoordinate.reduce((pre, cur) => {
    if (Number(cur)) {
      return Number(cur) < Number([pre]) && Number(cur) ? Number(cur) : Number(pre);
    } else {
      return Number([pre]);
    }
  }, maxrcY);
  maxrcY = (maxrcY * 1.2).toFixed(2);
  minrcY = (minrcY * 0.8).toFixed(2);
  return {
    minY,
    maxY,
    minrcY,
    maxrcY
  };
};

const labelLayoutFn = (data: any) => {
  const { minY, maxY, minrcY, maxrcY } = getMinYMaxY(data);
  const options: UtilsEChartsOption = {
    title: {
      text: "",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      },
      textStyle: {
        align: "left"
      },
      formatter: params => {
        let relVal = params[0].name;
        for (let i = 0; i < params.length; i++) {
          params[i].value = new Intl.NumberFormat("en-US").format(params[i].value);
          if (params[i].value == "NaN") {
            params[i].value = "-";
          }
          relVal += `<br/>${params[i].marker} ${params[i].seriesName} ${params[i].value} ${params[i].seriesName === "预测误差" ? "%" : getUnit.value}`;
        }
        return relVal;
      }
    },
    calculable: true, // 开启数据缩放
    legend: {
      // type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      top: 25,
      // data: props.areaList.map((item: any) => item.name),
      data: ["实际", "预测", "预测误差"],
      selected: {
        实际: true,
        预测: true,
        预测误差: false
      }
      // orient: "horizontal"
    },
    grid: {
      left: "0",
      // top: "15%",
      right: "0",
      bottom: "0",
      containLabel: true
    },
    // dataset: {
    //   source: arr
    // },
    xAxis: {
      type: "category",
      data: data.abscissa?.map(e => e) || [] // data.abscissa.map(e => e.substring(3))
    },
    yAxis: [
      {
        type: "value",
        name: `单位：${getUnit.value}`,
        alignTicks: true,
        nameTextStyle: {
          align: "left"
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        },
        axisLabel: {
          formatter: function (value) {
            return Number(value).toFixed(2);
          }
        },
        min: minY,
        max: maxY
      },
      {
        type: "value",
        // name: `%`,
        // position: "left",
        axisLabel: {
          formatter: function (value) {
            return Number(value).toFixed(2) + "%";
          }
        },
        // min: 0,
        // max: 100,
        // interval: 10,
        alignTicks: true,
        // offset: 50,
        axisLine: {
          show: true,
          lineStyle: {
            width: 1
          }
        },
        min: minrcY,
        max: maxrcY
      }
    ],
    dataZoom: [
      {
        show: false,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        start: 0,
        end: 100
      },
      {
        show: false,
        yAxisIndex: 0,
        filterMode: "empty",
        width: 30,
        height: "80%",
        showDataShadow: false,
        left: "93%"
      }
    ],
    series: [
      {
        name: "实际",
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#3B82F6"
        },
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        data: data.kwhCoordinate ? data.kwhCoordinate?.map(v => (v === null ? v : Number(transformNumber(v)))) : []
      },
      {
        name: "预测",
        type: "bar",
        barWidth: 16,
        yAxisIndex: 0,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#603BF6"
        },
        data: data.kwhPredictCoordinate ? data.kwhPredictCoordinate?.map(v => (v === null ? v : Number(transformNumber(v)))) : []
      },
      {
        name: "预测误差",
        type: "line",
        yAxisIndex: 1,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FFCA45"
        },
        data: data.radioCoordinate ? data.radioCoordinate.map(v => (v === null ? v : Number(v))) : []
      }
    ]
  };
  return options;
};
// 总排名
const labelLayoutAreaFn = async () => {
  const title = "";
  const param = {
    startDate: dateRangeItem.value[0],
    endDate: dateRangeItem.value[1],
    energyType: queryTypeParams.value.energyType === 1 ? Number(state.radioVal) : queryTypeParams.value.energyType
  };
  const res: any = await getBearPredictData(param);
  if (res.loadOview) {
    showCon.value = true;
    loadOviewData.value = res?.loadOview;
    yearOptions.value = res.loadOview.loadGraph ? labelLayoutFn(res.loadOview.loadGraph) : {};
  } else {
    loadOviewData.value = {};
    yearOptions.value = {};
  }
  midKey.value = Date.now();
};

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

interface queryForm {
  level?: string;
  startTime?: string;
  endTime?: string;
  month?: string | number;
}

const queryParams = ref<queryForm>({});

const queryTypeParams = ref({
  energyType: 1
});

const loading = ref(false);

const handleChangeTypeFn = (val: number) => {
  queryTypeParams.value.energyType = val;
  labelLayoutAreaFn();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  labelLayoutAreaFn();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 默认查询条件
const initQuery = () => {
  dateRangeItem.value = [getCurrentMonthF(), getCurrentMonthL()];
  labelLayoutAreaFn();
};
const changeMonth = () => {
  handleQuery();
};
/** 导出按钮操作 */
const handleDown = async () => {
  loadOviewData.value.loadGraph.dataUnit = getUnit.value;
  proxy.download("post", "/energy/energyPredictionStatistics/viewEnergyLoad/download", loadOviewData.value.loadGraph, `负荷预测.xlsx`);
};

onMounted(() => {
  initQuery();
});
const handleRadioChange = () => {
  handleQuery();
};
</script>

<style lang="scss" scoped>
.energy_consume {
  display: flex;
  flex-direction: column;
  gap: 16px;
  justify-content: flex-start;

  :deep(.px-empty .px-empty__image) {
    display: none !important;
  }

  .top_query {
    display: flex;
    flex-flow: row nowrap;
    width: 100%;
    min-width: 1300px;
    height: auto;
    padding: 16px 24px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;

    .tabs {
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;

      /*
      * tab样式
      */
      .tabSwitch {
        padding: 4px;
        margin-right: 20px;
        background-color: #f4f4f4;
        border-radius: 4px;

        :deep(.px-radio-button__inner) {
          background-color: #f4f4f4;
          border: none;
        }

        :deep(.is-active) {
          border: none;

          .px-radio-button__inner {
            background-color: var(--px-color-primary);
            border-radius: 4px;
          }
        }
      }
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .mid-bord {
    width: 100%;
    min-width: 1300px;
    height: 167px;
    background: #fff;
    border-radius: 4px;
  }

  .btn-con {
    display: flex;
    gap: 16px;
    justify-content: space-between;
    height: calc(100% - 76px);

    .btn-bord {
      position: relative;
      width: 100%;
      min-width: 1300px;
      background: #fff;
      border-radius: 4px;

      .rightBox {
        position: absolute;
        top: 16px;
        right: 20px;

        .selectMonth {
          width: 80px;
          margin-right: 15px;
        }
      }
    }
  }
}
</style>
